package org.darkforest.merchant.controller;

import org.darkforest.common.services.StoreClassService;
import org.darkforest.common.services.StoreJoinInService;
import org.darkforest.common.util.DateUtil;
import org.darkforest.common.util.JSONUtils;
import org.darkforest.controller.WebController;
import org.darkforest.dao.mapper.AreaMapper;
import org.darkforest.dao.mapper.StoreMapper;
import org.darkforest.model.Area;
import org.darkforest.model.Store;
import org.darkforest.model.StoreClass;
import org.darkforest.model.StoreJoinIn;
import org.darkforest.vo.MemberBase;
import org.darkforest.vo.StoreClassVo;
import org.darkforest.vo.StoreSellerVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by pc on 2017/12/11.
 */
@Controller
@RequestMapping("store")
public class StoreController extends WebController<StoreController> {
    @Autowired
    private StoreJoinInService storeJoinInService;
    @Autowired
    private AreaMapper areaMapper;
    @Autowired
    private StoreMapper storeMapper;
    @Autowired
    private StoreClassService storeClassService;
    @RequestMapping("view")
    public ModelAndView toEditJoin(HttpServletRequest request){
        ModelAndView view = new ModelAndView("store/view");
        StoreSellerVo sellerVo= (StoreSellerVo)request.getSession().getAttribute("sellerInfo");
        Store store = storeMapper.selectStoreByPrimaryKey(sellerVo.getStoreId());
        StoreJoinIn storeJoinIn = storeJoinInService.selectByPrimaryKey(store.getMemberId());
        if(storeJoinIn.getBusinessLicenceStart()!=null){
            storeJoinIn.setBusinessLicenceStart(DateUtil.strToDate(DateUtil.dateToString(storeJoinIn.getBusinessLicenceStart(), DateUtil.DEFAULT_DATE_PATTERN), DateUtil.DEFAULT_DATE_PATTERN));
        }
        if(storeJoinIn.getBusinessLicenceEnd()!=null){
            storeJoinIn.setBusinessLicenceEnd(DateUtil.strToDate(DateUtil.dateToString(storeJoinIn.getBusinessLicenceEnd(), DateUtil.DEFAULT_DATE_PATTERN), DateUtil.DEFAULT_DATE_PATTERN));
        }
        view.addObject("storeJoinIn",storeJoinIn);
        StoreClass storeClass = storeClassService.selectByPrimaryKey(storeJoinIn.getScId());
        view.addObject("storeClass",storeClass);
        List<Area> areas = areaMapper.getAreaListByParentId(0);
        view.addObject("areas",areas);
        if(storeJoinIn.getStoreClassIds()!= null){
            List<StoreClassVo> list= JSONUtils.toList(storeJoinIn.getStoreClassIds(), StoreClassVo.class);
            view.addObject("storeClassList", list);
        }
        return view;
    }
    @RequestMapping("update")
    public ModelAndView doEditJoin(MultipartHttpServletRequest multipartHttpServletRequest,HttpServletRequest request){
        StoreJoinIn storeJoinIn = new StoreJoinIn();
        // 图片格式CHECK
        String  errorTitle = "";
        // 营业执照电子版
        MultipartFile mpfCardPic1= multipartHttpServletRequest.getFile("businessLicenceNumberElectronic1");
        if(!mpfCardPic1.isEmpty()){
            errorTitle = errorTitle + picExtCheck("营业执照电子版", mpfCardPic1.getOriginalFilename());
        }

        // 组织机构代码证电子版
        MultipartFile organizationCodeElectronic= multipartHttpServletRequest.getFile("organizationCodeElectronic1");
        if(!organizationCodeElectronic.isEmpty()){
            errorTitle = errorTitle + picExtCheck("组织机构代码证电子版", organizationCodeElectronic.getOriginalFilename());
        }
        // 一般纳税人证明
        MultipartFile generalTaxpayer= multipartHttpServletRequest.getFile("generalTaxpayer1");
        if(!generalTaxpayer.isEmpty()){
            errorTitle = errorTitle + picExtCheck("一般纳税人证明", generalTaxpayer.getOriginalFilename());
        }
        // 开户银行许可证电子版
        MultipartFile mpfCardPic2= multipartHttpServletRequest.getFile("bankLicenceElectronic1");
        if(!mpfCardPic2.isEmpty()){
            errorTitle = errorTitle + picExtCheck("开户银行许可证电子版", mpfCardPic2.getOriginalFilename());
        }
        // 税务登记证号电子版
        MultipartFile mpfCardPic3= multipartHttpServletRequest.getFile("taxRegistrationCertificateElectronic1");
        if(!mpfCardPic3.isEmpty()){
            errorTitle = errorTitle + picExtCheck("税务登记证号电子版", mpfCardPic3.getOriginalFilename());
        }

        // 法人身份证正面
        MultipartFile legalPersonIdentityCardFront= multipartHttpServletRequest.getFile("legalPersonIdentityCardFront");
        if(!legalPersonIdentityCardFront.isEmpty()){
            errorTitle = errorTitle +  picExtCheck("法人身份证正面", legalPersonIdentityCardFront.getOriginalFilename());
        }
        // 法人身份证反面
        MultipartFile legalPersonIdentityCardBack= multipartHttpServletRequest.getFile("legalPersonIdentityCardBack");
        if(!legalPersonIdentityCardBack.isEmpty()){
            errorTitle = errorTitle + picExtCheck("法人身份证反面", legalPersonIdentityCardBack.getOriginalFilename());
        }
        // 商标授权书
        MultipartFile trademarkLicense= multipartHttpServletRequest.getFile("trademarkLicense");
        if(!trademarkLicense.isEmpty()){
            errorTitle = errorTitle + picExtCheck("商标授权书", trademarkLicense.getOriginalFilename());
        }
        // 销售授权书
        MultipartFile salesEmpowerment= multipartHttpServletRequest.getFile("salesEmpowerment");
        if(!salesEmpowerment.isEmpty()){
            errorTitle = errorTitle + picExtCheck("销售授权书", salesEmpowerment.getOriginalFilename());
        }
        // 商标注册证
        MultipartFile trademarkRegistrationCertificate= multipartHttpServletRequest.getFile("trademarkRegistrationCertificate");
        if(!trademarkRegistrationCertificate.isEmpty()){
            errorTitle = errorTitle + picExtCheck("商标注册证", trademarkRegistrationCertificate.getOriginalFilename());
        }
        // 检验检疫报告
        MultipartFile inspectionQuarantineReport= multipartHttpServletRequest.getFile("inspectionQuarantineReport");
        if(!inspectionQuarantineReport.isEmpty()){
            errorTitle = errorTitle + picExtCheck("检验检疫报告", inspectionQuarantineReport.getOriginalFilename());
        }
        // 卫生/生产许可证
        MultipartFile healthProductionPermit= multipartHttpServletRequest.getFile("healthProductionPermit");
        if(!healthProductionPermit.isEmpty()){
            errorTitle = errorTitle + picExtCheck("卫生/生产许可证", healthProductionPermit.getOriginalFilename());
        }
        // 食品流通许可证
        MultipartFile foodCirculationPermit= multipartHttpServletRequest.getFile("foodCirculationPermit");
        if(!foodCirculationPermit.isEmpty()){
            errorTitle = errorTitle + picExtCheck("食品流通许可证", foodCirculationPermit.getOriginalFilename());
        }
        // 其他
        MultipartFile otherMaterial= multipartHttpServletRequest.getFile("otherMaterial");
        if(!otherMaterial.isEmpty()){
            errorTitle = errorTitle + picExtCheck("其他证书", otherMaterial.getOriginalFilename());
        }
        if (errorTitle.length() > 0) {
            // 去掉最后一个、
            errorTitle = errorTitle.substring(0, errorTitle.length()-1);
            String errMsg = errorTitle + "图片格式不正确，请选择正确的图片!";

            ModelAndView modelAndView = new ModelAndView("message");
            modelAndView.addObject("msg", errMsg);
            return modelAndView;
        }

        // 图片上传
        // 营业执照电子版
        if(!mpfCardPic1.isEmpty()){
            String businessLicenceNumberElectronic =  super.uploadPicsWithoutCompressSize(mpfCardPic1, multipartHttpServletRequest, null, null);
            storeJoinIn.setBusinessLicenceNumberElectronic(businessLicenceNumberElectronic);
        }

        // 组织机构代码证电子版
        if(!organizationCodeElectronic.isEmpty()){
            String organizationCodeElectronic2 =  super.uploadPicsWithoutCompressSize(organizationCodeElectronic, multipartHttpServletRequest, null, null);
            storeJoinIn.setOrganizationCodeElectronic(organizationCodeElectronic2);
        }
        // 一般纳税人证明
        if(!generalTaxpayer.isEmpty()){
            String generalTaxpayer2 =  super.uploadPicsWithoutCompressSize(generalTaxpayer, multipartHttpServletRequest, null, null);
            storeJoinIn.setGeneralTaxpayer(generalTaxpayer2);
        }
        // 开户银行许可证电子版
        if(!mpfCardPic2.isEmpty()){
            String bankLicenceElectronic =  super.uploadPicsWithoutCompressSize(mpfCardPic2, multipartHttpServletRequest, null, null);
            storeJoinIn.setBankLicenceElectronic(bankLicenceElectronic);
        }
        // 税务登记证号电子版
        if(!mpfCardPic3.isEmpty()){
            String taxRegistrationCertificateElectronic =  super.uploadPicsWithoutCompressSize(mpfCardPic3, multipartHttpServletRequest, null, null);
            storeJoinIn.setTaxRegistrationCertificateElectronic(taxRegistrationCertificateElectronic);
        }
        String businessLicenceStart = multipartHttpServletRequest.getParameter("businessLicenceStartStr");
        String businessLicenceEnd = multipartHttpServletRequest.getParameter("businessLicenceEndStr");
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        try{
            if(businessLicenceStart!=null&&!businessLicenceStart.equals("")) storeJoinIn.setBusinessLicenceStart(sdf.parse(businessLicenceStart));
            if(businessLicenceEnd!=null&&!businessLicenceEnd.equals("")) storeJoinIn.setBusinessLicenceEnd(sdf.parse(businessLicenceEnd));
        }catch(Exception e) {
            e.printStackTrace();
        }

        // 法人身份证正面
        if(!legalPersonIdentityCardFront.isEmpty()){
            String legalPersonIdentityCardFront1 =  super.uploadPicsWithoutCompressSize(legalPersonIdentityCardFront, multipartHttpServletRequest, null, null);
            storeJoinIn.setLegalPersonIdentityCardFront(legalPersonIdentityCardFront1);
        }
        // 法人身份证反面
        if(!legalPersonIdentityCardBack.isEmpty()){
            String legalPersonIdentityCardBack1 =  super.uploadPicsWithoutCompressSize(legalPersonIdentityCardBack, multipartHttpServletRequest, null, null);
            storeJoinIn.setLegalPersonIdentityCardBack(legalPersonIdentityCardBack1);
        }
        // 商标授权书
        if(!trademarkLicense.isEmpty()){
            String trademarkLicense1 =  super.uploadPicsWithoutCompressSize(trademarkLicense, multipartHttpServletRequest, null, null);
            storeJoinIn.setTrademarkLicense(trademarkLicense1);
        }
        // 销售授权书
        if(!salesEmpowerment.isEmpty()){
            String salesEmpowerment1 =  super.uploadPicsWithoutCompressSize(salesEmpowerment, multipartHttpServletRequest, null, null);
            storeJoinIn.setSalesEmpowerment(salesEmpowerment1);
        }
        // 商标注册证
        if(!trademarkRegistrationCertificate.isEmpty()){
            String trademarkRegistrationCertificate1 =  super.uploadPicsWithoutCompressSize(trademarkRegistrationCertificate, multipartHttpServletRequest, null, null);
            storeJoinIn.setTrademarkRegistrationCertificate(trademarkRegistrationCertificate1);
        }
        // 检验检疫报告
        if(!inspectionQuarantineReport.isEmpty()){
            String inspectionQuarantineReport1 =  super.uploadPicsWithoutCompressSize(inspectionQuarantineReport, multipartHttpServletRequest, null, null);
            storeJoinIn.setInspectionQuarantineReport(inspectionQuarantineReport1);
        }
        // 卫生/生产许可证
        if(!healthProductionPermit.isEmpty()){
            String healthProductionPermit1 =  super.uploadPicsWithoutCompressSize(healthProductionPermit, multipartHttpServletRequest, null, null);
            storeJoinIn.setHealthProductionPermit(healthProductionPermit1);
        }
        // 食品流通许可证
        if(!foodCirculationPermit.isEmpty()){
            String foodCirculationPermit1 =  super.uploadPicsWithoutCompressSize(foodCirculationPermit, multipartHttpServletRequest, null, null);
            storeJoinIn.setFoodCirculationPermit(foodCirculationPermit1);
        }
        // 其他
        if(!otherMaterial.isEmpty()){
            String otherMaterial1 =  super.uploadPicsWithoutCompressSize(otherMaterial, multipartHttpServletRequest, null, null);
            storeJoinIn.setOtherMaterial(otherMaterial1);
        }

        StoreSellerVo sellerVo= (StoreSellerVo)request.getSession().getAttribute("sellerInfo");
        Store store = storeMapper.selectStoreByPrimaryKey(sellerVo.getStoreId());
        storeJoinIn.setMemberId(store.getMemberId());
        storeJoinIn.setCompanyProvinceId(0);
        storeJoinInService.updateStoreJoinInByPrimaryKey(storeJoinIn);
        ModelAndView view = new ModelAndView("redirect:/store/view");
        return view;
    }

    private  String picExtCheck(String title, String fileName) {

        int extIndex = fileName.lastIndexOf(".");
        String extName =  "";
        if (extIndex > 0) {
            extName = fileName.substring(extIndex);
        }
        // 图片文件后缀的判断
        if (!".PNG".equals(extName.toUpperCase()) && !".JPG".equals(extName.toUpperCase()) && !".JPEG".equals(extName.toUpperCase())) {
            return title + "、";
        }

        return "";
    }
}
